package metro.jme.lottery.graphics;

import java.io.IOException;
import java.util.Random;
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author pierre
 */
public class NumberSprite extends Sprite {
	
	private int currentPosX;
	private int currentPosY;
	private static final String image = "/numbers.png";
	private static final int FRAME_WIDTH = 100;
	private static final int FRAME_HEIGHT = 98;
	
	public static final int SEQ_SIZE = 30;
	private int frame; 
	
	private static final int MAX = 7;

	private NumberSprite(Image img, int frameWidth, int frameHeight, int x, int y, int winner) {
		super(img, frameWidth, frameHeight);
		currentPosX = x;
		currentPosY = y;
		setPosition(x, y);
		frame = 0;
		setFrameSequence(generateRandomSeq(winner));
	}
	
	public static NumberSprite createSprite(int x, int y, int winner) {
		try {
			Image img = Image.createImage(image);
			return new NumberSprite(img, FRAME_WIDTH, FRAME_HEIGHT, x, y, winner);
		} catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * @param winner
	 * @return 
	 */
	private int[] generateRandomSeq(int winner) {
		int[] seq = new int[SEQ_SIZE];
		Integer[] arrayOfIntegers = new Integer[MAX + 1];
		for (int i = 0; i < MAX + 1; i++) {
			arrayOfIntegers[i] = new Integer(i);
		}
		Vector pool = new Vector();
		for (int i = 0; i < MAX + 1; i++) {
			pool.addElement(arrayOfIntegers[i]);
		}

		for (int i = 0; i < pool.size(); i++) {
			System.out.println("pool.get = " + pool.elementAt(i));
		}
		Random rd = new Random();
		int rd_num = rd.nextInt(MAX);
		int next_rd = 0;
		pool.removeElement(arrayOfIntegers[rd_num]);
		
		for (int i = 1; i < SEQ_SIZE - 1; i++) {
			next_rd = rd.nextInt(MAX);
			System.out.println("next_rd = " + next_rd);
			seq[i] = ((Integer)pool.elementAt(next_rd)).intValue();
			// Add the value we previously deleted from pool
			pool.addElement(arrayOfIntegers[rd_num]);
			// Delete the last value generated
			pool.removeElement(arrayOfIntegers[next_rd]);
			// Switch values
			rd_num = next_rd;
		}
		
		seq[SEQ_SIZE-1] = winner;
		
		for (int i = 0; i < SEQ_SIZE; i++) {
			System.out.println("seq[i] = " + seq[i]);
		}
		return seq;
	}
	
	public boolean next() {
		if(frame < SEQ_SIZE - 1) {
			frame ++;
			return true;
		} else {
			return false;
		}
	}
	
	public boolean done() {
		return frame == SEQ_SIZE;
	}
	
}
